package utils

import (
	"sync"

	"golang.org/x/crypto/bcrypt"
)

var (
	cryptUtilTemp *cryptUtil
	cryptUtilOnce sync.Once
)

type cryptUtil struct{}

func NewCryptUtils() *cryptUtil {
	cryptUtilOnce.Do(func() {
		cryptUtilTemp = &cryptUtil{}
	})
	return cryptUtilTemp
}

func (m *cryptUtil) EnCrypt(password string) (string, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return "", err
	}
	return string(hash), err
}

func (m *cryptUtil) DeCrypt(hashedPassword, password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
	return err == nil
}
